package cn.com.nxt.txb;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.nim.uikit.permission.MPermission;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Timer;
import java.util.TimerTask;

import cn.com.nxt.txb.adapter.ViewPagerAdapter;
import cn.com.nxt.txb.fragment.BusinessFragment;
import cn.com.nxt.txb.fragment.CallFragment;
import cn.com.nxt.txb.fragment.HomeFragment;
import cn.com.nxt.txb.fragment.MineFragment;
import cn.com.nxt.txb.httpdelegate.BusinessDelegate;
import cn.com.nxt.txb.util.AppUtil;
import cn.com.nxt.txb.widget.FragmentTabHost;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
//    @ViewInject(R.id.viewpager)
//    private ViewPager viewPager;
//    @ViewInject(R.id.navigation)
    //private BottomNavigationView navigation;
    public static FragmentManager fm;
    FragmentTransaction ft;
    MenuItem prevMenuItem;
    private static final String EXTRA_APP_QUIT = "APP_QUIT";
    private static final int REQUEST_CODE_NORMAL = 1;
    private static final int REQUEST_CODE_ADVANCED = 2;
    private static final String TAG = MainActivity.class.getSimpleName();
    private final int BASIC_PERMISSION_REQUEST_CODE = 100;
    private Timer timer;
    private InvitationTask task;
    private BusinessDelegate delegate;
    private byte BUSINESS_FLAG= (byte) 0x80;
    /**
     * FragmentTabhost
     */
    private FragmentTabHost mTabHost;

    /**
     * 布局填充器
     *
     */
    private LayoutInflater mLayoutInflater;

    /**
     * Fragment数组界面
     *
     */
    private Class mFragmentArray[] = { HomeFragment.class, CallFragment.class,
            BusinessFragment.class, MineFragment.class };
    /**
     * 存放图片数组
     *
     */
    private int mImageArray[] = { R.drawable.tab_home, R.drawable.tab_call,
            R.drawable.tab_business, R.drawable.tab_mine };

    /**
     * 选修卡文字
     *
     */
    private String mTextArray[] = { "惠乐益", "电话", "通讯录", "我的" };

//    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
//            = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
//        @Override
//        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//            switch (item.getItemId()) {
//                case R.id.navigation_home:
//                    viewPager.setCurrentItem(0);
//                    //mTextMessage.setText("首页");
//                    return true;
//                case R.id.navigation_phone:
//                    viewPager.setCurrentItem(1);
//                    // mTextMessage.setText("电话");
//                    return true;
//                case R.id.navigation_video:
//                    viewPager.setCurrentItem(2);
//                    //mTextMessage.setText("共享中心");
//                    return true;
//                case R.id.navigation_mine:
//                    viewPager.setCurrentItem(3);
//                    //mTextMessage.setText("个人");
//                    return true;
//            }
//            return false;
//        }
//
//    };

    class InvitationTask extends TimerTask {

        @Override
        public void run(){
            if(mqttBinder==null||mqttBinder.isClientEmpty()){
                return;
            }
            timer.cancel();
           // mqttBinder.subscribe("/meetting/invlite/"+ AppUtil.mUser.getPhone());//监听会议邀请，客户端暂时不用实现
            //Log.i("111---","123321");
        }
    }

    private void subscribeInvitation(){
        timer.schedule(task, 1000, 2000);  //任务1 一秒钟后执行，每两秒执行一次。
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);//注解绑定
        delegate=new BusinessDelegate(this);
        fm = getSupportFragmentManager();

        mLayoutInflater = LayoutInflater.from(this);
        // 找到TabHost
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        // 得到fragment的个数
        int count = mFragmentArray.length;
        for (int i = 0; i < count; i++) {
            // 给每个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextArray[i]).setIndicator(
                    getTabItemView(i));
            // 将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, mFragmentArray[i], null);
        }
        mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);

        //showToast(AppUtil.mUser.getToken());
        Log.e("--token--",AppUtil.mUser.getToken());
        delegate.businessInfo(AppUtil.mUser.getToken(),BUSINESS_FLAG);
        requestBasicPermission();
        bindService(new Intent(MainActivity.this, MQTTService.class), this, BIND_AUTO_CREATE);
        timer = new Timer();
        task=new InvitationTask();
        subscribeInvitation();
        //SampleApplicationLike.mqttBinder.subscribe("/meetting/invlite/:"+ AppUtil.mUser.getPhone());
        // onParseIntent();
        //Bugly.init(getApplicationContext(), "dc3c3fbc0b", false);
        //setContentView(R.layout.activity_main);
        // viewPager= (ViewPager) findViewById(R.id.viewpager);
        // navigation = (BottomNavigationView) findViewById(R.id.navigation);
        //SampleApplicationLike.mqttBinder.setData("test_service");
//        int[][] states = new int[][]{
//                new int[]{-android.R.attr.state_checked},
//                new int[]{android.R.attr.state_checked}
//        };

//        int[] colors = new int[]{getResources().getColor(R.color.tabbar_normal_color),
//                getResources().getColor(R.color.main_color)
//        };
//        ColorStateList csl = new ColorStateList(states, colors);
//        navigation.setItemTextColor(csl);
//        navigation.setItemIconTintList(csl);
//
//        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                if (prevMenuItem != null) {
//                    prevMenuItem.setChecked(false);
//                } else {
//                    navigation.getMenu().getItem(0).setChecked(false);
//                }
//                navigation.getMenu().getItem(position).setChecked(true);
//                prevMenuItem = navigation.getMenu().getItem(position);
//
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });
//        setupViewPager(viewPager);
    }

    /**
     *
     * 给每个Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = mLayoutInflater.inflate(R.layout.tab_item_view, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageArray[index]);
        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextArray[index]);
        return view;
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(HomeFragment.newInstance("首页"));
        adapter.addFragment(CallFragment.newInstance("电话"));
        adapter.addFragment(BusinessFragment.newInstance("共享中心"));
        adapter.addFragment(MineFragment.newInstance("我", "我"));
        viewPager.setAdapter(adapter);
    }

//    private void onParseIntent() {
//        Intent intent = getIntent();
//        if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
//            IMMessage message = (IMMessage) getIntent().getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
//            switch (message.getSessionType()) {
//                case P2P:
//                    SessionHelper.startP2PSession(this, message.getSessionId());
//                    break;
//                case Team:
//                    SessionHelper.startTeamSession(this, message.getSessionId());
//                    break;
//                default:
//                    break;
//            }
//        } else if (intent.hasExtra(EXTRA_APP_QUIT)) {
//            onLogout();
//            return;
//        } else if (intent.hasExtra(AVChatActivity.INTENT_ACTION_AVCHAT)) {
//            if (AVChatProfile.getInstance().isAVChatting()) {
//                Intent localIntent = new Intent();
//                localIntent.setClass(this, AVChatActivity.class);
//                startActivity(localIntent);
//            }
//        } else if (intent.hasExtra(cn.com.nxt.txb.model.Extras.EXTRA_JUMP_P2P)) {
//            Intent data = intent.getParcelableExtra(cn.com.nxt.txb.model.Extras.EXTRA_DATA);
//            String account = data.getStringExtra(cn.com.nxt.txb.model.Extras.EXTRA_ACCOUNT);
//            if (!TextUtils.isEmpty(account)) {
//                SessionHelper.startP2PSession(this, account);
//            }
//        }
//    }

    // 注销
    private void onLogout() {
        // 清理缓存&注销监听
        //  LogoutHelper.logout();

        // 启动登录
        //LoginActivity.start(this);
        finish();
    }

    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.READ_PHONE_STATE,
            android.Manifest.permission.RECORD_AUDIO,
            android.Manifest.permission.ACCESS_COARSE_LOCATION,
            android.Manifest.permission.ACCESS_FINE_LOCATION
    };

    private void requestBasicPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(MainActivity.this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    /**
     * 再按一次退出系統
     */
    private long exitTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), R.string.again_exit,
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(this);
    }

    @Override
    public void success(String result, byte flag) {
        super.success(result, flag);
        JSONObject obj= null;
        try {
            obj = new JSONObject(result);
            SampleApplicationLike.businessName=obj.optString("name");
            SampleApplicationLike.businessID=obj.optString("bsid");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
